<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { showConfirmDialog, showSuccessToast } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

onMounted(() => {
  userStore.getUserProfile()
})

// 退出登录功能
const handleLogout = async () => {
  try {
    // 二次确认弹窗
    await showConfirmDialog({
      closeOnClickOverlay: true,
      title: '退出登录',
      message: '确定要退出登录吗？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })

    // 用户确认后，调用退出登录API
    await userStore.logout()

    // 显示成功提示
    showSuccessToast('退出登录成功')

    // 跳转到登录页面
    router.push('/login')
  } catch (error) {
    // 用户点击取消或其他错误，不做处理
    console.log('用户取消退出登录')
  }
}
</script>

<template>
  <div class="user-page">
    <div class="user">
      <van-image
        class="avatar"
        :src="`https://wsrv.nl/?url=${userStore.userProfile?.avatar}`"
        alt=""
      />
      <h3>{{ userStore.userProfile?.username }}</h3>
    </div>

    <van-grid clickable :column-num="3" :border="false">
      <van-grid-item icon="clock-o" text="历史记录" to="/" />
      <van-grid-item icon="bookmark-o" text="我的收藏" to="/collect" />
      <van-grid-item icon="thumb-circle-o" text="我的点赞" to="/like" />
    </van-grid>

    <van-cell-group class="mt20">
      <van-cell title="推荐分享" is-link />
      <van-cell title="意见反馈" is-link />
      <van-cell title="关于我们" is-link />
      <van-cell title="退出登录" is-link @click="handleLogout" />
    </van-cell-group>
  </div>
</template>

<style lang="scss" scoped>
.user-page {
  padding: 0 10px;
  background: #f5f5f5;
  height: 100vh;
  .mt20 {
    margin-top: 20px;
  }
  .user {
    display: flex;
    padding: 20px 0;
    align-items: center;

    .avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      overflow: hidden;
    }
    h3 {
      margin: 0;
      padding-left: 20px;
      font-size: 18px;
    }
  }
}
</style>
